package com.zhoupu.integrated.file.controller;

import com.zhoupu.integrated.file.service.IFileDownloadService;
import com.zhoupu.integrated.file.service.IFileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import software.amazon.awssdk.core.ResponseInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/file")
@Tag(name = "文件接口", description = "文件接口相关操作")
public class FileController {

    @Autowired
    private IFileUploadService iFileUploadService;

    @Autowired
    private IFileDownloadService iFileDownloadService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "直接上传文件返回文件地址")
    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("path") String path) throws Exception {

        InputStream inputStream = file.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);

        return iFileUploadService.upload(bytes,path,file.getOriginalFilename());
    }


    @PostMapping("/download")
    @Operation(summary = "下载文件", description = "直接下载文件返回文件地址")
    public String download(@RequestParam("path") String path) {

        return iFileDownloadService.downloadFile(path);

    }


    @PostMapping("/downloadBytes")
    @Operation(summary = "下载文件为字节数组", description = "直接下载文件返回字节数组")
    public ResponseEntity<byte[]> downloadBytes(@RequestParam("path") String path, @RequestParam("fileName") String fileName) {

         byte[] bytes = iFileDownloadService.downloadBytes(path);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, getFileName(fileName))
                .body(bytes);
     }

    private static String getFileName(String fileName) {
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replace("+", "%20");
        } catch (Exception e) {
            encodedFileName = "download.docx";
        }

        return "attachment; filename=\"" + encodedFileName + "\"";
    }

    @PostMapping("/downloadLargeFile")
    @Operation(summary = "下载文件为输入流", description = "直接下载文件返回输入流")
    public ResponseEntity<StreamingResponseBody> downloadLargeFile(@RequestParam("path") String path, @RequestParam("fileName") String fileName) {
        try {
            ResponseInputStream<?> inputStream = iFileDownloadService.downloadFileInputStream(path);

            // 创建 StreamingResponseBody
            StreamingResponseBody streamingBody = outputStream -> {
                try (inputStream) {
                    byte[] buffer = new byte[8192]; // 8KB 缓冲区
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        outputStream.flush();
                    }
                } catch (IOException e) {
                    throw new RuntimeException("文件流传输失败", e);
                }
            };

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, getFileName(fileName))
                    .body(streamingBody);

        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }



}
